package org.breathe.server.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.breathe.protocal.Resp;

import java.util.List;

/**
 * @author: breathe
 * @createTime: 2025-05-12
 */
@Slf4j
public class RespDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buffer, List<Object> list) throws Exception {
        try {
            if (buffer.readableBytes() > 0) {
                //这是啥意思
                buffer.markReaderIndex();
            }
            if (buffer.readableBytes() < 4) {
                //可读的字节 < 4
                return ;
            }
            try {
                //通过观看redis官网的resp，实现resp的解析
                Resp resp = Resp.decode(buffer);
                //log.info("decode resp: {}", resp);
                list.add(resp);
            } catch (Exception e) {
                log.error("decode error", e);
                buffer.resetReaderIndex();
                return ;
            }
        } catch (Exception e) {
            log.error("decode error", e);
        }
    }
}
